#include "StdAfx.h"
#include "step_out.h"


step_out_reader::step_out_reader(void)
{
}


step_out_reader::~step_out_reader(void)
{
}

int step_out_reader::read_file(const wchar_t* filename)
{
	int result = 0;

	data.clear();

	CStdioFile file;
	if(file.Open(filename,CFile::modeRead)==0)
		return -1;//open failed

	std::vector<char> buffer;
	int lenght = file.GetLength();

	buffer.resize(lenght+1);
	file.Read(&buffer[0],lenght);

	buffer[lenght] = '\0';

	int count = 0;
	int position = 0;
	int setnumber = 0;
	phase_space_dist dummy;
	char* stop  = nullptr;

	while(count!=3&&position<lenght)
	{
		if(buffer[position] == '\n')
			++count;
		++position;
	}//skip 3 lines


	while(position<lenght)
	{

		if(buffer[position]!='C'||buffer[position+1]!='o')
		{
			file.Close();
			return -2;//invalid file
		}

		data.push_back(dummy);
		position += 25;//Coordinate dump at phase xxxxxxxxxxx
		data[setnumber].phase = strtod(&buffer[position],&stop);

		do
		{
			position++;
		}while(buffer[position]!='\n'&&position<lenght);//search for newline

		position += 21;//Number of particles: xxxxxxxxx
		data[setnumber].size = strtol(&buffer[position],&stop,10);
		data[setnumber].dataset.resize(data[setnumber].size);

		do
		{
			position++;
		}while(buffer[position]!='\n'&&position<lenght);//search for newline, skip header
		do
		{
			position++;
		}while(buffer[position]!='\n'&&position<lenght);//search for newline

		for(int i=0;i<data[setnumber].size;i++)
		{
			data[setnumber].dataset[i].x = strtod(&buffer[position],&stop);
			data[setnumber].dataset[i].px = strtod(stop,&stop);
			data[setnumber].dataset[i].y = strtod(stop,&stop);
			data[setnumber].dataset[i].py = strtod(stop,&stop);
			data[setnumber].dataset[i].z = strtod(stop,&stop);
			data[setnumber].dataset[i].pz = strtod(stop,&stop);
			position+=95;//shift to line end
			do
			{
				position++;
			}while(buffer[position]!='\n'&&position<lenght);//search for newline
		}
		setnumber++;

		while(buffer[position]!='C'&&position<lenght)
			position++;

	}
	
	file.Close();

	return result;
}
